package cn.hncj.lyc.controller.pay;
import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;

import cn.hncj.lyc.bean.OrderManagement;
import cn.hncj.lyc.service.OrderStateService;
import cn.hncj.lyc.utils.wxpay.HttpClient;
import cn.hncj.lyc.utils.wxpay.IdWorker;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 拓薪教育 -- 腾讯课堂认证机构
 * 樱木老师void
 *
 * 调用统一下单的接口，根据微信支付服务器返回的结果生成支付二维码
 */
@Controller
@RequestMapping("/weixinpay")
//@WebServlet(name = "createNativeServlet",urlPatterns = "/createNativeServlet")
public class CreateNativeServlet extends HttpServlet {	
	
	@Autowired
	OrderStateService orderStateService;
	@RequestMapping("/wxgopay")
	public String wxpaysu(OrderManagement order,Model model) {		
		 try {
				
				orderStateService.updateOrderState(order);
				System.out.println(order+"111111");
				model.addAttribute("orderpayid", "成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				model.addAttribute("result", "修改用户信息失败");
			}
		return "pay/pay";		
	}

    /**
     * 调用微信统一下单接口，在微信端产生预支付订单
     * 根据返回的结果，生成二维码
     * HttpClient 发送请求 参数
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * 
     */	
    @RequestMapping("/wxpayDisplay")
    public void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	         //String orderNo = req.getParameter("orderId");
		try {
			// 创建HttpClient对象
			HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
			// 设置https
			client.setHttps(true);

			// 创建map集合
			Map<String, String> param = new HashMap();
			// 公众号
			param.put("appid", "wx0609f8351dca9750");
			// 商户号
			param.put("mch_id", "1536725911");
			// 随机字符串
			param.put("nonce_str", WXPayUtil.generateNonceStr());
			// 商品描述
    	            param.put("body", "乐购商城");
    	            // 订单的编号
    	            String orderNo = new IdWorker().nextId()+"";
    	            // 商户订单号
    	            param.put("out_trade_no", orderNo);
    	            System.out.println(orderNo);
    	            // 支付的金额
    	            String totalFee = "1";
    	            // 总金额（分）
    	            param.put("total_fee",totalFee);
    	            // IP
    	            param.put("spbill_create_ip", "127.0.0.1");
    	            // 回调地址
    	            param.put("notify_url", "http://www.txjava.cn/queryPayResult");
    	            // 交易类型
    	            param.put("trade_type", "NATIVE");
    	            // 生成签名，把map集合转换成xml格式的字符串
    	            // 1. 存放数据map  2. 申请的时候预留的密钥
    	            String xmlParam = WXPayUtil.generateSignedXml(param, "txjavayingmulaoshi01234567891234");
    	            // 请求https://api.mch.weixin.qq.com/pay/unifiedorder，传很多请求参数
    	            client.setXmlParam(xmlParam);
    	            // 发送请求
    	            client.post();
    	            // 获取到返回结果
    	            String content = client.getContent();
    	            // 使用工具类，解析content数据
    	            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);

    	            // 把订单编号 和 支付金额存入到resultMap
    	            resultMap.put("out_trade_no",orderNo);
    	            resultMap.put("total_fee",totalFee);

    	            // 响应
    	            resp.setContentType("application/json;charset=UTF-8");
    	            String resultStr = JSON.toJSONString(resultMap);
    	            resp.getWriter().print(resultStr);
    	            //System.out.println(resultStr);
    	           // System.out.println(resultMap.get("code_url"));
    	            
    	        } catch (Exception e) {
    	            e.printStackTrace();
    	        }
    		  
    	    }
}